// --------------------- 配置项 ------------------------------------------------------
let now_adcode = 500000; //所在地区编码
let big_center = [107.453921,30.196708];　//大地图中心点
let big_zoom = 8.32;　// 大地图大小
let big_Enable = false; // 大地图是否能移动
let samll_center = [107.87672,30.159249]; //小地图中心点
let small_zoom = 6.3;　//小地图大小
/**
 * 代码
 */
var isMassMark = 0;
/**-------------------------------------- 主地图 ---------------------------------*/
var map = new AMap.Map("container", {
    zoom: big_zoom, //地图级别
    // center: [107.174401,27.007983],//地图中心
    center: big_center, //地图中心
    mapStyle: 'amap://styles/blue',
    viewMode: '3D',
    rotateEnable:big_Enable,
    dragEnable:big_Enable,
    scrollWheel:big_Enable,
    doubleClickZoom:big_Enable
});
/**-------------------------------------- 行政区下钻 ---------------------------------*/

AMapUI.load(['ui/geo/DistrictExplorer', 'lib/$'], function (DistrictExplorer, $) {
    //创建一个实例
    let districtExplorer = window.districtExplorer = new DistrictExplorer({
        eventSupport: true, //打开事件支持
        map: map
    });
    let node_all;
    //当前聚焦的区域
    let currentAreaNode = null;

    //鼠标hover提示内容
    // var $tipMarkerContent = $("<div class='tipMarker top'></div>");

    let $tipMarkerContent = $('<div style="color:white;font-size:3px"></div>');
    // let $tipMarkerContent = $('<div style="color: white;font-size: 3px;font-family: 微软雅黑" face="微软雅黑" size="3" color="#FFFFFF"></div>');

    let tipMarker = new AMap.Marker({
        content: $tipMarkerContent.get(0),
        offset: new AMap.Pixel(0, 0),
        bubble: true,
        zIndex: 20,
        // eventSupport:false
    });

    //根据Hover状态设置相关样式
    function toggleHoverFeature(feature, isHover, position) {

        tipMarker.setMap(isHover ? map : null);

        if (!feature) {
            return;
        }

        let props = feature.properties;

        if (isHover) {

            //更新提示内容
            $tipMarkerContent.html(props.name);
            //更新位置
            tipMarker.setPosition(position || props.center);
        }

        $('#area-tree').find('h2[data-adcode="' + props.adcode + '"]').toggleClass('hover', isHover);

        //更新相关多边形的样式
        let polys = districtExplorer.findFeaturePolygonsByAdcode(props.adcode);
        for (let i = 0, len = polys.length; i < len; i++) {

            polys[i].setOptions({
                fillOpacity: isHover ? 0.5 : 0.2
            });
        }
    }

    //监听feature的hover事件
    districtExplorer.on('featureMouseout featureMouseover', function (e, feature) {
        toggleHoverFeature(feature, e.type === 'featureMouseover',
            e.originalEvent ? e.originalEvent.lnglat : null);
    });

    //监听鼠标在feature上滑动
    districtExplorer.on('featureMousemove', function (e) {
        //更新提示位置
        tipMarker.setPosition(e.originalEvent.lnglat);
    });

    //feature被点击
    districtExplorer.on('featureClick', function (e, feature) {

        let props = feature.properties;

        //如果存在子节点
        if (props.childrenNum > 0) {
            //切换聚焦区域
            switch2AreaNode(props.adcode);
        } else {
            if (isMassMark === 0) {
                // var node =  switch1AreaNode(props.adcode);
                render(node_all);
                map.setZoom(11);
                map.setCenter(props.center);
                tipMarker.setMap(null);
            } else {
                isMassMark = 0;
            }
        }
    });

    function render(areaNode) {
        //更新地图视野
        // map.setBounds(areaNode.getBounds(), null, null, true);

        //清除已有的绘制内容
        districtExplorer.clearFeaturePolygons();

        //绘制子区域
        districtExplorer.renderSubFeatures(areaNode, function () {

            // let fillColor = colors[i % colors.length];
            // var strokeColor = colors[colors.length - 1 - i % colors.length];
            let strokeColor = "#FFFFFF";

            return {
                cursor: 'default',
                bubble: true,
                strokeColor: strokeColor, //线颜色
                strokeOpacity: 1, //线透明度
                strokeWeight: 1, //线宽
                fillColor: null, //填充色
                fillOpacity: 0, //填充透明度
            };
        });

        //绘制父区域
        districtExplorer.renderParentFeature(areaNode, {
            cursor: 'default',
            bubble: true,
            strokeColor: '#FFFFFF', //线颜色
            strokeOpacity: 1, //线透明度
            strokeWeight: 1, //线宽
            fillColor: null, //填充色
            fillOpacity: 0.35, //填充透明度
        });
    }

    //绘制某个区域的边界
    function renderAreaPolygons(areaNode) {
        node_all = areaNode;
        //更新地图视野
        // map.setBounds(areaNode.getBounds(), null, null, true);
        map.setZoom(big_zoom);
        // map.setZoom(8);
        //清除已有的绘制内容
        districtExplorer.clearFeaturePolygons();

        //绘制子区域
        districtExplorer.renderSubFeatures(areaNode, function () {

            // var fillColor = colors[i % colors.length];
            // var strokeColor = colors[colors.length - 1 - i % colors.length];
            var strokeColor = '#FFFFFF';

            return {
                cursor: 'default',
                bubble: true,
                strokeColor: strokeColor, //线颜色
                strokeOpacity: 1, //线透明度
                strokeWeight: 1, //线宽
                fillColor: null, //填充色
                fillOpacity: 0.35, //填充透明度
            };
        });

        //绘制父区域
        districtExplorer.renderParentFeature(areaNode, {
            cursor: 'default',
            bubble: true,
            strokeColor: '#FFFFFF', //线颜色
            strokeOpacity: 1, //线透明度
            strokeWeight: 1, //线宽
            fillColor: null, //填充色
            fillOpacity: 0.35, //填充透明度
        });
    }

    //切换区域后刷新显示内容
    function refreshAreaNode(areaNode) {

        districtExplorer.setHoverFeature(null);

        renderAreaPolygons(areaNode);

        //更新选中节点的class
        let $nodeEles = $('#area-tree').find('h2');

        $nodeEles.removeClass('selected');

        let $selectedNode = $nodeEles.filter('h2[data-adcode=' + areaNode.getAdcode() + ']').addClass('selected');

        //展开下层节点
        $selectedNode.closest('li').removeClass('hide-sub');

        //折叠下层的子节点
        $selectedNode.siblings('ul.sublist').children().addClass('hide-sub');
    }

    //切换区域
    function switch2AreaNode(adcode, callback) {

        if (currentAreaNode && ('' + currentAreaNode.getAdcode() === '' + adcode)) {
            return;
        }

        loadAreaNode(adcode, function (error, areaNode) {

            if (error) {

                if (callback) {
                    callback(error);
                }

                return;
            }

            currentAreaNode = window.currentAreaNode = areaNode;

            //设置当前使用的定位用节点
            districtExplorer.setAreaNodesForLocating([currentAreaNode]);

            refreshAreaNode(areaNode);

            if (callback) {
                callback(null, areaNode);
            }
        });
    }

    // function switch1AreaNode(adcode) {
    //     let node = districtExplorer.loadAreaNode(adcode, function (error, areaNode) {
    //         return areaNode;
    //     });
    //     return node;
    // }

    //加载区域
    function loadAreaNode(adcode, callback) {

        districtExplorer.loadAreaNode(adcode, function (error, areaNode) {

            if (error) {

                if (callback) {
                    callback(error);
                }

                // console.error(error);

                return;
            }

            if (callback) {
                callback(null, areaNode);
            }
        });
    }

    //重庆
    switch2AreaNode(now_adcode);
});
/**-------------------------------------- 右键菜单 ---------------------------------*/
var menu = new ContextMenu(map);

//自定义菜单类
function ContextMenu(map) {
    let me = this;

    //地图中添加鼠标工具MouseTool插件
    // this.mouseTool = new AMap.MouseTool(map);

    // this.contextMenuPositon = null;

    let content = [];

    content.push("<div class='info context_menu'>");
    content.push("<p onclick='menu.back()'>返回</p>");
    content.push("</div>");

    //通过content自定义右键菜单内容
    this.contextMenu = new AMap.ContextMenu({
        isCustom: true,
        content: content.join('')
    });

    //地图绑定鼠标右击事件——弹出右键菜单
    map.on('rightclick', function (e) {
        me.contextMenu.open(map, e.lnglat);
        me.contextMenuPositon = e.lnglat; //右键菜单位置
    });
}

ContextMenu.prototype.back = function () {
    map.setZoom(big_zoom);
    let ln = new AMap.LngLat(big_center[0],big_center[1]);
    map.setCenter(ln);
};

/**-------------------------------------- 工作人员标注 ---------------------------------*/
//-------------------- 定时更新数据 --------------------------
// setInterval(get_isworkon, 5000);
// get_isworkon();

// //------------ axios 获取数据 -----------
// function get_isworkon() {
//     axios
//         .get('/d/isworking')
//         .then(function (response) {
//             // 取数据
//             let data = response.data.working_list;
//             // 组织数据
//             let position_info = [];
//             for (let item in data) {
//                 if (!data.hasOwnProperty(item)) continue;
//                 let info = data[item];
//                 let p_list = info['location'];
//                 let name = info['name'];
//                 let phone = info['phone'];
//                 position_info.push({
//                     position: p_list[0],
//                     name: name,
//                     mobile: phone
//                 });
//             }
//             // 标点
//             render_point(position_info);
//         })
//         .catch(function (error) {
//             console.log(error);
//         })
// }

//---------- 标点 ---------------
function render_point(info_list) {
    clearSimplemarker(marker_list);
    marker_list = [];
    for (let item in info_list) {
        if (!info_list.hasOwnProperty(item)) continue;
        let info = info_list[item];
        // alert(info.position);
        let marker = new AMap.Marker({
            position: str_to_lnglat(info.position),
            label: {
                offset: new AMap.Pixel(30, 2),
                content: "<div class='label' style='color: black'>" + info['name'] + "</div>"
            },
            icon: get_icon('/image/4.png')
        });
        marker_event(marker, info);
        marker_list.push(marker);
        marker.setMap(map);
    }
}

//---------- 标点添加事件 ---------------
function marker_event(marker, info) {
    // 构造绑定事件
    marker.on('click', function () {
        map.setZoom(15);
        map.setCenter(this.getPosition());
    });
    marker.on('mouseover', function () {
        // alert(i);
        title = '检测人员';
        let info_ = "<div><span style='color: #FFFFFF'>电话：" + info.mobile + "</span><span style='color: #FFFFFF'> 地址：" + info.address + "</span></div>";
        infoWindow.setContent(updateInfoWindow(info.name, info_));
        infoWindow.open(map, this.getPosition());
    });
    marker.on('mouseout', function () {
        closeInfoWindow();
    });
}

//---------- 新建信息窗口 ---------------
var title = '监测人员';
var content = '';
var infoWindow = new AMap.InfoWindow({
    isCustom: true, //使用自定义窗体
    content: createInfoWindow(title, content),
    offset: new AMap.Pixel(16, -45)
});

//---------- 构建信息窗口 ---------------
function createInfoWindow(title, content) {
    let info = document.createElement("div");
    info.className = "custom-info input-card content-window-card";

    //可以通过下面的方式修改自定义窗体的宽高
    //info.style.width = "400px";
    // 定义顶部标题
    let top = document.createElement("div");
    let titleD = document.createElement("div");
    let closeX = document.createElement("img");
    top.className = "info-top";
    titleD.innerHTML = title;
    closeX.src = "https://webapi.amap.com/images/close2.gif";
    closeX.onclick = closeInfoWindow;

    top.appendChild(titleD);
    top.appendChild(closeX);
    info.appendChild(top);

    // 定义中部内容
    let middle = document.createElement("div");
    middle.className = "info-middle";
    middle.style.backgroundColor = 'rgb(0,0,0,0.5)';
    middle.innerHTML = content;
    info.appendChild(middle);

    // 定义底部内容
    let bottom = document.createElement("div");
    bottom.className = "info-bottom";
    bottom.style.position = 'relative';
    bottom.style.top = '0px';
    bottom.style.margin = '0 auto';
    let sharp = document.createElement("img");
    sharp.src = "https://webapi.amap.com/images/sharp.png";
    bottom.appendChild(sharp);
    info.appendChild(bottom);
    return info;
}

//动态更新信息窗口
function updateInfoWindow(title, content) {
    return createInfoWindow(title, content);
}

//关闭信息窗体
function closeInfoWindow() {
    map.clearInfoWindow();
}


//------------------------------------- 工具 ----------------------------------
//----------- 清除多余点 -----------------
var marker_list = [];

function clearSimplemarker(ob_list) {
    if (ob_list.length > 0) {
        for (let i = 0; i < ob_list.length; i++) {
            map.remove(ob_list[i]);
        }
    }
}

//----------- 处理字符串坐标 --------------
//接收字符串坐标，返回坐标对象
function str_to_lnglat(position_str) {
    let position = position_str.split(',');
    return new AMap.LngLat(parseFloat(position[0]), parseFloat(position[1]));
}

///----------- 获取样式 -------------------
//传入图片路径字符串，返回样式
function get_icon(url) {
    return new AMap.Icon({
        size: new AMap.Size(40, 40),
        image: url,
        imageSize: new AMap.Size(35, 40),
    });
}

/**-------------------------------------- 黑广播海量点标注 ---------------------------------*/
//--------------------------- 设置海量点 -----------------------------

let style = [{
    url: 'https://a.amap.com/jsapi_demos/static/images/mass0.png',
    anchor: new AMap.Pixel(6, 6),
    size: new AMap.Size(11, 11)
}];
var mass = new AMap.MassMarks([], {
    opacity: 0.8,
    zIndex: 200,
    cursor: 'pointer',
    style: style,
    alwaysRender: false
});

function setMassMark(data, mass) {
    let title = '黑广播';
    let content = '';
    let infoWindow = new AMap.InfoWindow({
        isCustom: true, //使用自定义窗体
        content: createInfoWindow(title, content),
        offset: new AMap.Pixel(16, -45)
    });


    // let style = [
    //     {
    //         url: 'https://a.amap.com/jsapi_demos/static/images/mass0.png',
    //         anchor: new AMap.Pixel(6, 6),
    //         size: new AMap.Size(11, 11)
    //     }
    // ];
    // mass.setStyle(style);
    mass.setData(data);
    // let mass = new AMap.MassMarks(data, {
    //     opacity: 0.8,
    //     zIndex: 200,
    //     cursor: 'pointer',
    //     style: style,
    //     alwaysRender: false
    // });
    mass.on('mouseover', function (e) {
        let data = e.data.data;
        // console.log(data);
        let address = e.data.address;
        // console.log(address);
        let lnglat = e.data.lnglat;
        let info_ = '<div  style="border-bottom: solid;border-color: white"><div class="indexInfoFont">' + address + '</div></div>';
        for (let item in data) {
            if (!data.hasOwnProperty(item)) continue;
            let infoData = data[item];
            // alert(infoData.Channel);
            info_ += "<span class='indexInfoFont'>频点：" + (Number(infoData.freq) / 10).toFixed(2) + " " + "</span>";
            info_ += "<span class='indexInfoFont'>" + infoData.category + "</span></br>";
        }
        infoWindow.setContent(updateInfoWindow('黑广播', info_));
        infoWindow.open(map, lnglat);
    });
    mass.on('mouseout', function () {
        closeInfoWindow();
    });
    mass.on('click', function (e) {
        isMassMark = 1;
        let lnglat = e.data.lnglat;
        map.setZoom(15);
        map.setCenter(lnglat);
    });
    mass.setMap(map);
    return mass;

}

//--------------------------- 获取数据 -------------------------------
// axios.get('/d/bigscreen/massmark').then(function (response) {
//     setMassMark(response.data.data, mass);
// });
/**-------------------------------------- 热力图 ---------------------------------*/
var map2 = new AMap.Map('container2', {
    mapStyle: 'amap://styles/blue',
    zoom: small_zoom,
    viewMode: "3D",
    center: samll_center, //地图中心
    // center: new AMap.LngLat(107.624225, 30.211628),
    rotateEnable: false,
    dragEnable: false,
    scrollWheel: false,
    doubleClickZoom: false,
    // center: new AMap.LngLat(106.504962, 29.533155)
});

let heatdata = [];
// axios
//     .get('/d/broadcast/heat')
//     .then(function (response) {
//         let location_list = response.data.location_list;
//         for (let item in location_list) {
//             if (!location_list.hasOwnProperty(item)) continue;
//             let location = location_list[item].split(',');
//             heatdata.push({
//                 lng: location[0],
//                 lat: location[1],
//                 count: 10
//             })
//         }
//         setheat();
//     });
var heatmap;
setheat();

function setheat() {
    //map为高德地图实例，AMap.Heatmap为高德地图热力图插件
    map.plugin(["AMap.Heatmap"], function () {
        heatmap = new AMap.Heatmap(map2, {
            radius: 20, //给定半径
            opacity: [0, 0.9],
            gradient: {
                0.5: '#2c7bb6',
                0.65: '#abd9e9',
                0.7: '#ffffbf',
                0.9: '#fde468',
                1.0: '#d7191c'
            }
        });
        heatmap.setDataSet({
            data: heatdata
        });
    });
}


function ResetHeat(heatdata) {
    heatmap.setDataSet({
        data: heatdata
    });
}

var colors = [
    // "#05607D",
    "#00FFF0",
    // "#4D4D4D"
    // "#3366cc", "#dc3912", "#ff9900", "#109618", "#990099", "#0099c6", "#dd4477", "#66aa00",
    // "#b82e2e", "#316395", "#994499", "#22aa99", "#aaaa11", "#6633cc", "#e67300", "#8b0707",
    // "#651067", "#329262", "#5574a6", "#3b3eac"
];

AMapUI.load(['ui/geo/DistrictExplorer', 'lib/$'], function (DistrictExplorer, $) {
    //创建一个实例
    let districtExplorer = window.districtExplorer = new DistrictExplorer({
        eventSupport: true, //打开事件支持
        map: map2
    });
    let node_all;
    //当前聚焦的区域
    let currentAreaNode = null;

    //鼠标hover提示内容

    //绘制某个区域的边界
    function renderAreaPolygons(areaNode) {
        node_all = areaNode;
        //更新地图视野
        // map.setBounds(areaNode.getBounds(), null, null, true);
        // map.setZoom(8);
        //清除已有的绘制内容
        districtExplorer.clearFeaturePolygons();

        //绘制子区域
        districtExplorer.renderSubFeatures(areaNode, function () {

            // var fillColor = colors[i % colors.length];
            // var strokeColor = colors[colors.length - 1 - i % colors.length];
            let strokeColor = "#FFFFFF";

            return {
                cursor: 'default',
                bubble: true,
                strokeColor: strokeColor, //线颜色
                strokeOpacity: 1, //线透明度
                strokeWeight: 1, //线宽
                fillColor: null, //填充色
                fillOpacity: 0.35, //填充透明度
            };
        });

        //绘制父区域
        districtExplorer.renderParentFeature(areaNode, {
            cursor: 'default',
            bubble: true,
            strokeColor: '#FFFFFF', //线颜色
            strokeOpacity: 1, //线透明度
            strokeWeight: 1, //线宽
            fillColor: null, //填充色
            fillOpacity: 0.35, //填充透明度
        });
    }


    //切换区域后刷新显示内容
    function refreshAreaNode(areaNode) {
        // alert(areaNode);
        districtExplorer.setHoverFeature(null);

        renderAreaPolygons(areaNode, 'null');

        //更新选中节点的class
        var $nodeEles = $('#area-tree').find('h2');

        $nodeEles.removeClass('selected');

        var $selectedNode = $nodeEles.filter('h2[data-adcode=' + areaNode.getAdcode() + ']').addClass('selected');

        //展开下层节点
        $selectedNode.closest('li').removeClass('hide-sub');

        //折叠下层的子节点
        $selectedNode.siblings('ul.sublist').children().addClass('hide-sub');
    }

    //加载区域
    function loadAreaNode(adcode, callback) {

        districtExplorer.loadAreaNode(adcode, function (error, areaNode) {

            if (error) {
                if (callback) {
                    callback(error);
                }
                console.error(error);
                return;
            }

            currentAreaNode = window.currentAreaNode = areaNode;

            //设置当前使用的定位用节点
            districtExplorer.setAreaNodesForLocating([currentAreaNode]);

            refreshAreaNode(areaNode);

            if (callback) {
                callback(null, areaNode);
            }
        });
    }

    //重庆
    // loadAreaNode(500000);
    loadAreaNode(now_adcode);

});
/**-------------------------------------- 行政区蒙板 ---------------------------------*/
var colorsMengban = {};
var getColorBySoc = function (adcode, this_adcode) {
    if (adcode) {
        if (!colorsMengban[adcode]) {
            if (adcode === this_adcode) {
                return null;
            }
            return '#033447'
            // return '#FFFFFF'
        }
    } else {
        return null
    }
};
var disCountry = new AMap.DistrictLayer.Country({
    zIndex: 19,
    SOC: 'CHN',
    depth: 1,
    styles: {
        'fill': function (props) {
            return getColorBySoc(props.adcode_pro, now_adcode)
        }
    }
});
let disCountry2 = new AMap.DistrictLayer.Country({
    zIndex: 19,
    SOC: 'CHN',
    depth: 1,
    styles: {
        'fill': function (props) {
            // return getColorBySoc(props.adcode_pro, 500000)
            return getColorBySoc(props.adcode_pro, now_adcode);
        }
    }
});
map.add(disCountry);
map2.add(disCountry2);
// --------------------- 通过拖动或缩放获取当前地图缩放级别和中心点坐标 ----------------------------------
// ************* 拖动获取当前中心点坐标 ********************

map.on("moveend",function(e){
    console.log(map.getCenter());
});
map2.on("moveend",function(e){
    console.log(map2.getCenter());
});

// ************* 缩放获取当前地图缩放级别 ******************
map.on("zoomend",function(){
    console.log(map.getZoom());
});
map2.on("zoomend",function(){
    console.log(map2.getZoom());
});